'use strict';

const Controller = require('egg').Controller;
const jwt = require("jsonwebtoken")
class HomeController extends Controller {
    async login() {
        const { app, ctx } = this
        const { username, password } = ctx.request.body
        // console.log(username);
        const data = await app.mysql.query(`select * from logins where username = "${username}" and password = "${password}"`)
        //遍历登录成功的数据存入到datas
        const datas = data.map(item => {
            return {
                type: item.type,
                username: item.username,
                img: item.img
            }
        })

        if (data.length) {
            //登陆成功传入datas
            ctx.body = {
                code: 1,
                datas,
                token: jwt.sign({ ...data }, '1901B', { expiresIn: '3m' }),
            }
        } else {
            ctx.body = {
                code: 0,
            }
        }
    }

    async regis() {
        const { ctx, app } = this;
        const { username, password } = ctx.request.body;
        const data = await app.mysql.get('logins', { username })
        if (data) {
            ctx.body = {
                code: "000",
                msg: "账号已存在",
                data
            }
        } else {
            await app.mysql.insert('logins', { username, password })
            ctx.body = {
                code: "001",
                msg: "注册成功",
                data
            }
        }
    }
}

module.exports = HomeController;
